<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企业名称" prop="loaComNo">
        <el-select v-model="queryParams.loaComNo" filterable placeholder="请选择企业名称" clearable size="small">
          <el-option
            v-for="dict in companiesName"
            :key="dict.comId"
            :label="dict.comName"
            :value="dict.comId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="银行名称" prop="loaBankId">
        <el-select v-model="queryParams.loaBankId" filterable placeholder="请选择银行">
          <el-option
            v-for="dict in bankNames"
            :key="dict.bankId"
            :label="dict.bankName"
            :value="dict.bankId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="贷款编号" prop="loaNo">
        <el-input
          v-model="queryParams.loaNo"
          placeholder="请输入贷款编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="贷款用途" prop="loaUse">
        <el-input
          v-model="queryParams.loaUse"
          placeholder="请输入贷款用途"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="贷款利率" prop="loaRate">
        <el-input
          v-model="queryParams.loaRate"
          placeholder="请输入贷款利率"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="贷款状态" prop="loaState">
        <el-select v-model="queryParams.loaState" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in sysBankLoaStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="贷款时间" prop="loaTime">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.loaTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择贷款时间"
        />
      </el-form-item>
      <el-form-item label="贷款金额" prop="loaMoney">
        <el-input
          v-model="queryParams.loaMoney"
          placeholder="请输入贷款金额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:loans:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="loansList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="loaId" />
      <el-table-column label="贷款编号" align="center" prop="loaNo" />
      <el-table-column label="企业名称" align="center" prop="company.comName" />
      <el-table-column label="银行名称" align="center" prop="bank.bankName" />
      <el-table-column label="贷款期限(月)" align="center" prop="loaLisId" />
      <el-table-column label="贷款用途" align="center" prop="loaUse" />
      <el-table-column label="贷款利率" align="center" prop="loaRate" />
      <el-table-column label="贷款时间" align="center" prop="loaTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loaTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="贷款金额(￥)" align="center" prop="loaMoney" />
      <el-table-column label="贷款状态" align="center" prop="loaState">
        <template slot-scope="scope">
          <dict-tag :options="sysBankLoaStatus" :value="scope.row.loaState" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:loans:edit']"
            :disabled="scope.row.loaState === '4'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:loans:remove']"
          >删除</el-button>
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['system:loans:loan']"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>审批
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="handleLoanDetails"
                icon="el-icon-circle-check"
                v-hasPermi="['system:loans:loan']"
                :disabled="scope.row.loaState === '4'"
              >进入审批</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="form-border"
      >
        <!-- 贷款ID显示（修改时可见，确保ID存在） -->
        <el-form-item v-if="form.loaId" label="贷款ID" prop="loaId">
          <el-input v-model="form.loaId" placeholder="贷款ID" disabled />
        </el-form-item>

        <el-form-item label="企业名称" prop="loaComNo">
          <el-select
            v-model="form.loaComNo"
            filterable
            placeholder="请选择企业名称"
            clearable
            size="small"
            @change="() => $refs.form.validateField('loaComNo')"
          >
            <el-option
              v-for="dict in companiesName"
              :key="dict.comId"
              :label="dict.comName"
              :value="dict.comId + ''"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="银行名称" prop="loaBankId">
          <el-select
            v-model="form.loaBankId"
            filterable
            placeholder="请选择银行"
            clearable
            size="small"
            @change="() => $refs.form.validateField('loaBankId')"
          >
            <el-option
              v-for="dict in bankNames"
              :key="dict.bankId"
              :label="dict.bankName"
              :value="dict.bankId + ''"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="贷款期限(月)" prop="loaLisId">
          <el-input
            v-model="form.loaLisId"
            placeholder="请输入贷款期限（单位：月）"
            clearable
            size="small"
            @input="handleNumberInput('loaLisId')"
          />
        </el-form-item>

        <el-form-item label="贷款用途" prop="loaUse">
          <el-input
            v-model="form.loaUse"
            placeholder="请输入贷款用途"
            clearable
          />
        </el-form-item>

        <el-form-item label="贷款积分" prop="loaIntegral">
          <el-input
            v-model="form.loaIntegral"
            placeholder="请输入贷款积分（可选）"
            clearable
            size="small"
            @input="handleNumberInput('loaIntegral')"
          />
        </el-form-item>

        <el-form-item label="贷款利率" prop="loaRate">
          <el-input
            v-model="form.loaRate"
            placeholder="请输入贷款利率（如：5.6 表示5.6%）"
            clearable
            @input="handleNumberInput('loaRate')"
          />
        </el-form-item>

        <el-form-item label="贷款状态" prop="loaState">
          <el-select
            v-model="form.loaState"
            placeholder="请选择贷款状态"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in sysBankLoaStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="贷款时间" prop="loaTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.loaTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择贷款时间"
          />
        </el-form-item>

        <el-form-item label="贷款金额" prop="loaMoney">
          <el-input
            v-model="form.loaMoney"
            placeholder="请输入贷款金额（单位：元）"
            clearable
            @input="handleNumberInput('loaMoney')"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="submitLoading" @click="cancel">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLoans,
  getLoans,
  delLoans,
  addLoans,
  updateLoans,
  exportLoans,
  listBankLoans,
  getBankNames,
  getLoansNo
} from "@/api/system/loans";
import { getAptitudeCompanyName } from "@/api/system/aptitude";

export default {
  name: "Loans",
  data() {
    return {
      loading: true,
      exportLoading: false,
      submitLoading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      loansList: [],
      companiesName: [],
      sysBankLoaStatus: [],
      bankNames: [],
      loansNoOptions: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        loaNo: null,
        loaComNo: null,
        loaBankId: null,
        loaLisId: null,
        loaUse: null,
        loaIntegral: null,
        loaRate: null,
        loaState: null,
        loaTime: null,
        loaMoney: null
      },
      form: {
        loaId: null, // 确保初始化时存在该字段
        loaNo: null,
        loaComNo: null,
        loaBankId: null,
        loaLisId: null,
        loaUse: null,
        loaIntegral: null,
        loaRate: null,
        loaState: null,
        loaTime: null,
        loaMoney: null,
        loaDel: null
      },
      rules: {
        loaComNo: [
          { required: true, message: "请选择企业名称", trigger: ["change", "blur"] },
          { type: "string", message: "企业选择错误", trigger: ["change", "blur"] }
        ],
        loaBankId: [
          { required: true, message: "请选择银行名称", trigger: ["change", "blur"] },
          { type: "string", message: "银行选择错误", trigger: ["change", "blur"] }
        ],
        loaLisId: [
          { required: true, message: "请输入贷款期限", trigger: ["blur", "input"] },
          { pattern: /^\d+$/, message: "贷款期限必须为正整数（如12）", trigger: ["blur", "input"] }
        ],
        loaUse: [
          { required: true, message: "请输入贷款用途", trigger: ["blur", "input"] },
          { min: 1, max: 50, message: "贷款用途长度不能超过50字", trigger: ["blur", "input"] }
        ],
        loaRate: [
          { required: true, message: "请输入贷款利率", trigger: ["blur", "input"] },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "贷款利率必须为数字，最多保留2位小数", trigger: ["blur", "input"] }
        ],
        loaState: [
          { required: true, message: "请选择贷款状态", trigger: ["change", "blur"] }
        ],
        loaTime: [
          { required: true, message: "请选择贷款时间", trigger: ["change", "blur"] }
        ],
        loaMoney: [
          { required: true, message: "请输入贷款金额", trigger: ["blur", "input"] },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "贷款金额必须为数字，最多保留2位小数", trigger: ["blur", "input"] }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getListComName();
    this.getListBankName();
    this.getListLoansNo();
    this.getDicts("sys_bankloan_status").then(response => {
      this.sysBankLoaStatus = response.data;
    });
  },
  methods: {
    /** 查询贷款列表 */
    getList() {
      this.loading = true;
      listBankLoans(this.queryParams)
        .then(response => {
          // 确保每条记录都有loaId，避免表格行数据缺失
          this.loansList = (response.rows || []).map(item => ({
            ...item,
            loaId: item.loaId || null // 明确赋值，避免undefined
          }));
          this.total = response.total || 0;
        })
        .catch(error => {
          this.$message.error("获取列表失败：" + (error.msg || error.message));
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 表单重置 */
    reset() {
      this.form = {
        loaId: null,
        loaNo: null,
        loaComNo: null,
        loaBankId: null,
        loaLisId: null,
        loaUse: null,
        loaIntegral: null,
        loaRate: null,
        loaState: null,
        loaTime: null,
        loaMoney: null,
        loaDel: null
      };
      this.resetForm("form");
      this.submitLoading = false;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.loaId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 查询银行列表 */
    getListBankName() {
      getBankNames()
        .then(response => {
          this.bankNames = response.data || [];
        })
        .catch(error => {
          this.$message.error("获取银行列表失败：" + (error.msg || error.message));
        });
    },

    /** 查询贷款编号列表 */
    getListLoansNo() {
      getLoansNo()
        .then(response => {
          this.loansNoOptions = response.data || [];
        })
        .catch(error => {
          this.$message.error("获取贷款编号列表失败：" + (error.msg || error.message));
        });
    },

    /** 更多操作触发 */
    handleCommand(command, row) {
      switch (command) {
        case "handleLoanDetails":
          this.handleLoanDetails(row);
          break;
        default:
          break;
      }
    },

    /** 查看审批详情 */
    handleLoanDetails(row) {
      const beId = row.loaId;
      if (!beId) {
        this.$message.error("请选择有效的贷款记录（贷款ID为空）");
        return;
      }
      this.$router.push("/bankLoans/bankLoanDetails/" + beId);
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加贷款";
    },

    /** 修改按钮操作 - 核心修复：确保loaId正确传递 */
    handleUpdate(row) {
      this.reset();
      // 1. 强制校验row中的loaId是否存在
      const loaId = row.loaId;
      if (loaId === null || loaId === undefined || loaId === '') {
        this.$message.error('选择的贷款记录无效，未找到贷款ID');
        return;
      }

      // 2. 提前将loaId存入form，防止接口返回异常时丢失
      this.form.loaId = loaId;

      // 3. 调用接口获取详情
      getLoans(loaId)
        .then(response => {
          const data = response.data || {};
          // 4. 适配表单数据，保留loaId
          this.form = {
            ...data,
            loaId: loaId, // 强制使用表格行的loaId，确保正确性
            loaComNo: data.loaComNo ? data.loaComNo + "" : null,
            loaBankId: data.loaBankId ? data.loaBankId + "" : null
          };
          this.open = true;
          this.title = "修改贷款";
          console.log("修改操作 - 表单数据:", this.form); // 调试用
        })
        .catch(error => {
          this.$message.error("获取贷款详情失败：" + (error.msg || error.message));
        });
    },

    /** 查询已实名企业列表 */
    getListComName() {
      getAptitudeCompanyName()
        .then(response => {
          this.companiesName = response.data || [];
        })
        .catch(error => {
          this.$message.error("获取企业列表失败：" + (error.msg || error.message));
        });
    },

    /** 处理数字输入 */
    handleNumberInput(field) {
      if (!this.form[field]) {
        this.form[field] = "";
        return;
      }
      // 正整数处理
      if (field === "loaLisId" || field === "loaIntegral") {
        this.form[field] = this.form[field].replace(/[^0-9]/g, "");
      }
      // 带小数的数字处理
      else if (field === "loaRate" || field === "loaMoney") {
        this.form[field] = this.form[field].replace(/[^0-9.]/g, "");
        const parts = this.form[field].split(".");
        if (parts.length > 1) {
          this.form[field] = parts[0] + "." + (parts[1].slice(0, 2) || "");
        }
      }
    },

    /** 提交按钮 - 核心修复：强化loaId校验 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          this.$message.error("表单填写有误，请检查后重试");
          return;
        }

        // 修改操作必须有有效的loaId
        if (this.title === "修改贷款") {
          if (!this.form.loaId) {
            this.$message.error("修改失败：未获取到贷款ID");
            this.submitLoading = false;
            return;
          }

          // 转换为数字类型并校验
          const loaIdNum = Number(this.form.loaId);
          if (isNaN(loaIdNum) || loaIdNum <= 0) {
            this.$message.error("修改失败：贷款ID必须是正整数");
            this.submitLoading = false;
            return;
          }
          this.form.loaId = loaIdNum;
        }

        // 处理提交数据类型转换
        const submitData = {
          ...this.form,
          loaLisId: this.form.loaLisId ? Number(this.form.loaLisId) : null,
          loaIntegral: this.form.loaIntegral ? Number(this.form.loaIntegral) : null,
          loaRate: this.form.loaRate ? Number(this.form.loaRate) : null,
          loaMoney: this.form.loaMoney ? Number(this.form.loaMoney) : null,
          loaComNo: this.form.loaComNo ? Number(this.form.loaComNo) : null,
          loaBankId: this.form.loaBankId ? Number(this.form.loaBankId) : null
        };

        console.log("提交到后端的数据:", submitData); // 调试用

        this.submitLoading = true;
        const request = this.title === "修改贷款" ? updateLoans : addLoans;
        request(submitData)
          .then(response => {
            this.$message.success(this.title === "修改贷款" ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          })
          .catch(error => {
            this.$message.error(`${this.title}失败：${error.msg || error.message}`);
          })
          .finally(() => {
            this.submitLoading = false;
          });
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const loaIds = row.loaId || this.ids;
      if (!loaIds || (Array.isArray(loaIds) && loaIds.length === 0)) {
        this.$message.error("请选择要删除的贷款记录");
        return;
      }

      this.$confirm(
        `是否确认删除选中的贷款数据?`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => delLoans(loaIds))
        .then(() => {
          this.$message.success("删除成功");
          this.getList();
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm("是否确认导出所有符合条件的贷款数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.exportLoading = true;
          return exportLoans(this.queryParams);
        })
        .then(response => {
          this.download(response.msg);
          this.$message.success("导出成功");
        })
        .catch(() => {})
        .finally(() => {
          this.exportLoading = false;
        });
    }
  }
};
</script>

<style scoped>
.form-border {
  border: 1px solid #e6e6e6;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
}
.el-form-item__error {
  color: #f56c6c !important;
  font-weight: 500;
  margin-top: 4px;
}
.el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #606266;
  cursor: not-allowed;
}
</style>
